// 获取存储的token
export const getToken = (): string | null => {
  return localStorage.getItem('token');
};

// 设置token
export const setToken = (token: string): void => {
  localStorage.setItem('token', token);
};

// 移除token
export const removeToken = (): void => {
  localStorage.removeItem('token');
};

// 检查token是否存在
export const hasToken = (): boolean => {
  return !!getToken();
};

// 解析JWT token（简单版本，生产环境建议使用专门的库）
export const parseJwt = (token: string): any => {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    );
    return JSON.parse(jsonPayload);
  } catch (error) {
    console.error('解析JWT token失败:', error);
    return null;
  }
};

// 检查token是否过期
export const isTokenExpired = (token: string): boolean => {
  try {
    const decoded = parseJwt(token);
    if (!decoded || !decoded.exp) {
      return true;
    }
    
    const currentTime = Date.now() / 1000;
    return decoded.exp < currentTime;
  } catch (error) {
    return true;
  }
};

// 获取token中的用户信息
export const getUserFromToken = (token: string): any => {
  try {
    const decoded = parseJwt(token);
    return decoded ? {
      userId: decoded.userId,
      username: decoded.username,
      role: decoded.role
    } : null;
  } catch (error) {
    return null;
  }
};
